﻿using BudgetData;
using BudgetSV.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BudgetSV.admin
{
    public class ManagePage : System.Web.UI.Page
    {//protected internal Model.siteconfig siteConfig;
        public string basepath = "";
        public ManagePage()
        {
            this.Load += new EventHandler(ManagePage_Load);
            //siteConfig = new BLL.siteconfig().loadConfig();
        }

        //protected override void OnInit(EventArgs e)
        //{
        //    base.OnInit(e);
        //    this.Unload += new EventHandler(Page_Unload);
        //}

        //protected virtual void Page_Unload(object sender, EventArgs e)
        //{
        //    return;
        //}

        /// <summary>
        /// 绑定处室领导
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string BindLeader(Manager model)
        {
            string LiderHtml = "";
            var lds = Mod.GetList<Manager>(c => c.org_id == model.org_id && (c.depart_id == model.depart_id || c.depart_id == 0) && c.isleader).OrderBy(s => s.sort).ToList();// && c.depart_id == model.depart_id
            if (lds.Count == 0)
            {
                LiderHtml = "<tr style=\"height:25px;\">" +
          "<td style=\"width:20%;text-align:center;\"></td>" +
              "" +
          "<td style=\"width:80%;\">未定义领导...</td>" +
      "</tr>";
            }
            else
            {
                var lds0 = lds.Where(c => c.depart_id == 0).ToList();
                if (lds0.Count > 0)
                {
                    LiderHtml += "<tr style=\"height:25px;\">" +
              "<td colspan=\"2\" style=\"text-align:left;\">&nbsp;&nbsp;" + (model.org_id == 1 ? "厅" : "局") + "领导</td>" +
          "</tr>";
                    foreach (var l in lds0)
                    {
                        if (l.id != model.id)
                        {
                            LiderHtml += "<tr style=\"height:25px;\">" +
    "<td style=\"width:20%;text-align:center;\">" +
    "<input class=\"roleit\" type=\"checkbox\" onchange=\"lederchange('" + l.id + "');\" value=\"" + l.id + "\" data-name=\"" + l.real_name + "\" /></td>" +
    "<td style=\"width:80%;\">" + l.real_name + "</td>" +
    "</tr>";
                        }
                    }
                }
                var lds1 = lds.Where(c => c.depart_id == model.depart_id).ToList();
                if (lds1.Count > 0)
                {
                    LiderHtml += "<tr style=\"height:25px;\">" +
              "<td colspan=\"2\" style=\"text-align:left;\">&nbsp;&nbsp;处室领导</td>" +
          "</tr>";
                    foreach (var l in lds1)
                    {
                        if (l.id != model.id)
                        {
                            LiderHtml += "<tr style=\"height:25px;\">" +
    "<td style=\"width:20%;text-align:center;\">" +
    "<input class=\"roleit\" type=\"checkbox\" onchange=\"lederchange('" + l.id + "');\" value=\"" + l.id + "\" data-name=\"" + l.real_name + "\" /></td>" +
    "<td style=\"width:80%;\">" + l.real_name + "</td>" +
    "</tr>";
                        }
                    }
                }
            }
            return LiderHtml;
        }

        private void ManagePage_Load(object sender, EventArgs e)
        {
            basepath = Server.MapPath("~");
            //判断管理员是否登录
            if (!IsAdminLogin())
            {
                var url = Request.Url.ToString();
                if (!url.Contains("/login.aspx"))
                {
                    Response.Write("<script>parent.location.href='/admin/login.aspx'</script>");
                    Response.End();
                }
            }
        }

        #region 管理员============================================
        /// <summary>
        /// 判断管理员是否已经登录(解决Session超时问题)
        /// </summary>
        public bool IsAdminLogin()
        {
            //如果Session为Null
            if (Session[DTKeys.SESSION_ADMIN_INFO] != null)
            {
                return true;
            }
            else
            {
                //检查Cookies
                string adminname = Utils.GetCookie("AdminName", "Budget");
                string adminpwd = Utils.GetCookie("AdminPwd", "Budget");
                if (adminname != "" && adminpwd != "")
                {
                    Manager model = Mod.GetModel<Manager>(c=>c.user_name==adminname&&c.password==adminpwd);
                    if (model != null)
                    {
                        Session[DTKeys.SESSION_ADMIN_INFO] = model;
                        return true;
                    }
                }
            }
            return false;
        }
        public Manager GetLoginModel(string user_name, string password, bool is_encrypt)
        {
            var u = Mod.GetModel<Manager>(c => c.user_name == user_name);
            //检查一下是否需要加密
            if (is_encrypt)
            {
                //先取得该用户的随机密钥
                string salt = u.salt;
                if (string.IsNullOrEmpty(salt))
                {
                    return null;
                }

                //把明文进行加密重新赋值
                password = DESEncrypt.Encrypt(password, salt);
            }
            if (u.password == password) { return u; }
            else { return null; }
        }
        /// <summary>
        /// 取得管理员信息
        /// </summary>
        public Manager GetAdminInfo()
        {
            if (IsAdminLogin())
            {
                Manager model = Session[DTKeys.SESSION_ADMIN_INFO] as Manager;
                if (model != null)
                {
                    return model;
                }
            }
            return null;
        }

        /// <summary>
        /// 检查管理员权限
        /// </summary>
        /// <param name="nav_name">菜单名称</param>
        /// <param name="action_type">操作类型</param>
        public void ChkAdminLevel(string nav_name, string action_type)
        {
            Manager model = GetAdminInfo();
            bool result = model.role_type > 1 ? Ifexistnvactval(model.id, nav_name, action_type) : true;
            if (result == false && action_type == "View") { result = Ifexistnvactval(model.id, nav_name, "Show"); }
            if (result == false && action_type == "Show") { result = Ifexistnvactval(model.id, nav_name, "View"); }
            if (!result)
            {
                string msgbox = "parent.jsdialog(\"错误提示\", \"您没有管理该页面的权限，请勿非法进入！\", \"back\", \"Error\")";
                Response.Write("<script type=\"text/javascript\">" + msgbox + "</script>");
                Response.End();
            }
        }

        public bool Ifexistnvactval(long id, string nav_name, string action_type)
        {
            var h= Mod.GetList<ManagerRoleValue>("SELECT * from ManagerRoleValue where role_id in (SELECT role_id FROM ManagerRoleLK WHERE manager_id="+id+") and nav_name='"+ nav_name + "' AND action_type='"+ action_type + "'").FirstOrDefault();
            return h == null ? false : true;
        }

        /// <summary>
        /// 写入管理日志
        /// </summary>
        /// <param name="action_type"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        public bool AddAdminLog(string action_type, string remark)
        {
            //if (siteConfig.logstatus > 0)
            //{
            Manager model = GetAdminInfo();
            var m = Mod.Add(new ManagerLog() {
                user_id=model.id,
                user_name= model.user_name,
                action_type= action_type,
                remark= remark,
                org_id= model.depart_id,
                add_time=DateTime.Now,
                user_ip= DTRequest.GetIP()
            });
            if (m.id > 0)
            {
                return true;
            }
            //}
            return false;
        }

        #endregion

        #region JS提示============================================
        /// <summary>
        /// 添加编辑删除提示
        /// </summary>
        /// <param name="msgtitle">提示文字</param>
        /// <param name="url">返回地址</param>
        /// <param name="msgcss">CSS样式</param>
        protected void JscriptMsg(string msgtitle, string url, string msgcss)
        {
            string msbox = "parent.jsprint(\"" + msgtitle + "\", \"" + url + "\", \"" + msgcss + "\")";
            ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox, true);
        }
        /// <summary>
        /// 带回传函数的添加编辑删除提示
        /// </summary>
        /// <param name="msgtitle">提示文字</param>
        /// <param name="url">返回地址</param>
        /// <param name="msgcss">CSS样式</param>
        /// <param name="callback">JS回调函数</param>
        protected void JscriptMsg(string msgtitle, string url, string msgcss, string callback)
        {
            string msbox = "parent.jsprint(\"" + msgtitle + "\", \"" + url + "\", \"" + msgcss + "\", " + callback + ")";
            ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox, true);
        }
        protected void Jscript(string js)
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "JsPrint", js, true);
        }
        #endregion

        /// <summary>
        /// 获取到市级的列表（总共只处理3级）
        /// </summary>
        /// <param name="parent_id"></param>
        /// <returns></returns>
        public List<Organization> GetLevel2(long parent_id)
        {
            var datals1 = new List<Organization>();

            if (parent_id != null)
            {
                var tdt = Mod.GetModel<Organization>(c=>c.id==parent_id);
                datals1.Add(tdt);
            }

            datals1.AddRange(Mod.GetList<Organization>("select * from Organization where parent_id="+parent_id+ " and is_department=0 order by class_layer, sort_id"));
            return datals1;
        }

        public List<Organization> GetAllList(long? parent_id)
        {
            var list = Mod.GetList<Organization>("select * from Organization order by class_layer, sort_id");
            var datals = new List<Organization>();
            var datals1 = new List<Organization>();

            if (parent_id != null)
            {
                var tdt = Mod.GetModel<Organization>(c => c.id == parent_id);
                datals1.Add(tdt);
            }

            datals1.AddRange(Addallchils(datals, list, parent_id));
            return datals1;
        }

        public List<Organization> Addallchils(List<Organization> datals, List<Organization> list, long? pid)
        {
            foreach (var l in list.Where(c => c.parent_id == pid && c.is_lock == 0))
            {
                datals.Add(l);
                var chils = list.Where(c => c.parent_id == l.id).ToList();
                if (chils.Count > 0) { datals = Addallchils(datals, list, l.id); }
            }
            return datals;
        }
        public List<Organization> GetList(long? parent_id)
        {
            var list = Mod.GetList<Organization>("select * from Organization where is_department=0 order by class_layer, sort_id");
            var datals = new List<Organization>();
            var datals1 = new List<Organization>();
            var datals2 = new List<Organization>();
            if (parent_id != null)
            {
                var tdt = Mod.GetModel<Organization>(c => c.id == parent_id);
                datals1.Add(tdt);
            }

            datals1.AddRange(Addchils(datals, list, parent_id));
            return datals1;
        }
        public List<Organization> Addchils(List<Organization> datals, List<Organization> list, long? pid)
        {
            foreach (var l in list.Where(c => c.parent_id == pid))
            {
                datals.Add(l);
                //由于只显示本级和一级子级，所以不用递归了；
                //var chils = list.Where(c => c.id == l.id).ToList();
                //if (chils.Count > 0) { datals = Addchils(datals, list, l.id); }
            }
            return datals;
        }
        public List<Department> GetDepartList(long? orgid)
        {
            var list = Mod.GetList<Department>("select * from Department where org_id="+ orgid + " order by class_layer, sort_id");
            var datals = new List<Department>();
            datals = AddDepartchils(datals, list, null);

            return datals;
        }
        public List<Department> AddDepartchils(List<Department> datals, List<Department> list, long? pid)
        {
            foreach (var l in list.Where(c => c.parent_id == pid))
            {
                datals.Add(l);
                var chils = list.Where(c => c.id == l.id).ToList();
                if (chils.Count > 0) { datals = AddDepartchils(datals, list, l.id); }
            }
            return datals;
        }
        public List<Navigation> GetNavList(int? parent_id, string nav_type)
        {
            var list = Mod.GetList<Navigation>("select * from Navigation order by class_layer, sort_id");
            var datals = new List<Navigation>();
            datals = AddNavchils(datals, list, null);

            return datals;
        }

        public List<Navigation> GetNavList(long org_id, int? parent_id, string nav_type)
        {
            var list = Mod.GetList<Navigation>("select * from Navigation where name='sys_business' or name='xinxiCaibian' or org_id=" + org_id + " order by class_layer, sort_id");
            var datals = new List<Navigation>();
            datals = AddNavchils(datals, list, null);

            return datals;
        }

        public List<Navigation> AddNavchils(List<Navigation> datals, List<Navigation> list, long? pid)
        {
            foreach (var l in list.Where(c => c.parent_id == pid))
            {
                datals.Add(l);
                var chils = list.Where(c => c.id == l.id).ToList();
                if (chils.Count > 0) { datals = AddNavchils(datals, list, l.id); }
            }
            return datals;
        }
        public Organization GetOrgBymanager(long mnid) {
            var m = Mod.GetModel<Manager>(c => c.id == mnid);
            var org = Mod.GetModel<Organization>(c => c.id == m.org_id);
            return org;
        }
    }
}
